package com.example.demo01.Entity.websocketEntity;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @ServerEndPoint WebSocket注解，表示当前类可用于实现Websocket通信
 */
@Component
@ServerEndpoint("/websocket")//WebSocket访问地址
public class WebSocket {
    private Session session;
    //WebSocket容器，存储Session实例
    private static CopyOnWriteArraySet<WebSocket> webSocketSet=new CopyOnWriteArraySet<>();

    //对应前端的请求
    /**
     * 打开连接
     * */
    @OnOpen
    public void onOpen(Session session){
        this.session=session;
        webSocketSet.add(this);
        System.out.println("【websocket消息】有新的连接，总数{"+webSocketSet.size()+"}");
    }


    /**
     * 关闭连接
     * */
    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        System.out.println("【websocket消息】连接断开，总数{"+webSocketSet.size()+"}");
    }

    /**
     * 接收消息:监听前端发送过来的新消息
     * */
    @OnMessage
    public void onMessage(String message){
        System.out.println("【websocket消息】收到客户端发来的消息{"+message+"}");
    }

    /**
     * 发送消息
     * */
    public void sendMessage(String message){
        //遍历存储的WebSocket实例
        for (WebSocket webSocket : webSocketSet){
            //广播消息
            System.out.println("【websocket消息】广播消息{"+message+"}");
            //发送消息
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
